package com.acme.bankapp.service.bank;

import java.util.LinkedList;
import java.util.List;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.exception.ClientExistsException;
import com.acme.bankapp.listeners.ClientRegistrationListener;
import com.acme.bankapp.listeners.DebugListener;
import com.acme.bankapp.listeners.EmailNotificationListener;
import com.acme.bankapp.listeners.PrintClientListener;

public class BankService {

    private List<ClientRegistrationListener> listeners = new LinkedList<>();
    private Bank bank;
    
    public void addClient(Client newClient)
	    throws ClientExistsException {
	for (int i = 0; i < Bank.CLIENTS_MAX; i++) {
	    Client[] clients = bank.getClients();
	    if (clients[i] == null) {
		clients[i] = newClient;
		for (ClientRegistrationListener listener : listeners) {
		    listener.onClientAdded(newClient);
		}
		break;
	    } else if (clients[i].equals(newClient)) {
		throw new ClientExistsException("Client already exists!");
	    }
	}
    }

    /**
     * @param listeners
     */
    public BankService(Bank bank, List<ClientRegistrationListener> listeners) {
	super();
	this.bank = bank;
	this.listeners = listeners;
    }
    
    

    /**
     * 
     */
    public BankService(Bank bank) {
	super();
	this.bank = bank;
	PrintClientListener printer = new PrintClientListener();
	EmailNotificationListener mailNotif = new EmailNotificationListener();
	DebugListener debug = new DebugListener();
	listeners.add(printer);
	listeners.add(mailNotif);
	listeners.add(debug);
    }

    public void printBalance() {
	for (Client client : bank.getClients()) {
	    if (client != null) {
		System.out.println(client.toString() + "'s balance: "
			+ client.getAccount().getBalance());
	    }
	}
    }

    public void printMaximumAmountToWithdraw() {
	for (Client client : bank.getClients()) {
	    if (client != null) {
		System.out.println(client + "'s max.amount to withdraw: "
			+ client.getAccount().maximumAmountToWithdraw());
	    }
	}
    }

    /**
     * @return the clients
     */
    public Client getClient(String clientName) {
	Client result = null;
	Client[] clients = bank.getClients();
	for (int i = 0; i < Bank.CLIENTS_MAX; i++) {
	    if (clients[i] != null && clients[i].getName().equals(clientName)) {
		result = clients[i];
	    }
	}
	return result;
    }
}
